import { useSelector, useDispatch } from 'react-redux'
import { useCallback } from 'react'
import type { RootState, AppDispatch } from '../store/store'
import {
  setUserInfo,
  setToken,
  loginSuccess,
  logout,
  setLoading,
  updateUserInfo,
  selectUserInfo,
  selectIsLoggedIn,
  selectToken,
  selectUserLoading,
  type UserInfo,
  selectAuthHeaders,
} from '../store/userSlice'

// 使用用户状态的hook
export const useUser = () => {
  const dispatch = useDispatch<AppDispatch>()
  
  // 获取用户状态
  const userInfo = useSelector(selectUserInfo)
  const isLoggedIn = useSelector(selectIsLoggedIn)
  const token = useSelector(selectToken)
  const loading = useSelector(selectUserLoading)
  const authHeaders = useSelector(selectAuthHeaders)

  // 设置用户信息
  const setUser = useCallback((userInfo: UserInfo) => {
    dispatch(setUserInfo(userInfo))
  }, [dispatch])

  // 设置token
  const setUserToken = useCallback((token: string) => {
    dispatch(setToken(token))
  }, [dispatch])

  // 登录成功
  const handleLoginSuccess = useCallback((userInfo: UserInfo, token?: string) => {
    dispatch(loginSuccess({ userInfo, token }))
  }, [dispatch])

  // 登出
  const handleLogout = useCallback(() => {
    dispatch(logout())
  }, [dispatch])

  // 设置加载状态
  const setUserLoading = useCallback((loading: boolean) => {
    dispatch(setLoading(loading))
  }, [dispatch])

  // 更新用户信息
  const updateUser = useCallback((userInfo: Partial<UserInfo>) => {
    dispatch(updateUserInfo(userInfo))
  }, [dispatch])

  return {
    // 状态
    userInfo,
    isLoggedIn,
    token,
    loading,
    authHeaders,
    // 方法
    setUser,
    setUserToken,
    handleLoginSuccess,
    handleLogout,
    setUserLoading,
    updateUser
  }
}
